#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Read WDC data files
Copyright (C) 2014 Christian T. Steigies <steigies@physik.uni-kiel.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"

## --------------------------------------------------------------------------
import os
import sys
import calendar # monthrange, isleap
from datetime import datetime, date, time

from nmdb.station.station_data import check_data, check_pressure

## --------------------------------------------------------------------------
wdc_station = [ "ahmd" , "chic", "zugs" ]
#"albu", "alrt", "alma", "almb", "apty" ]
# map nmdb station names to WDC station names
wdc_map = {
    "ahmd": "AHMEDA", "albu": "ALBUQU", "alrt": "ALERT", "alma": "ALMA_A", "almb": "ALMA_B", "apty":"APATIT",
    "athn": "ATHENS",
    "bgnr": "BAGNER", "bksn": "BAKSAN", "brbg": "BARENT", "bjng": "BEIJIN", "bert": "BEIRUT", "berk": "BERKEL", 
    "brbn":"BRISBA", "bnsa": "BUENOS", "bure": "BURE",
    "calg": "CALGAR", "caps": "CAPE_S", "casy": "CASEY", "ctly": "CHACAL", "chic": "CHICAG", "chrh":"CHURCH", 
    "clmx": "CLIMAX", "cllg": "COLLEG", "cord": "CORDOB",
    "dlls": "DALLAS", "drwn": "DARWIN", "deep": "DEEP_R", "dnvr": "DENVER", "drbs": "DOURBE", "drhm": "DURHAM",
#"ELLSWO", "EREVAN", "EREVN3", "ESOISR",
#"FORT_S", "FREIBU", "FUKUSH",
#"GOOSE", "GOTTIN",
#"HAFELE", "HALESM", "HALIGY", "HALLE", "HEISS", "HERMAN", "HERSTM", "HOBART", "HUANCA",
#"INTHAN", "INUVIK", "INVERC", "IRKUT2", "IRKUT3", "IRKUTS",
#"JUNG64", "JUNGFR",
    "kmpl": "KAMPAL", "kerg": "KERGUE", "khbr": "KHABAR", "kiel": "KIEL", "kiev": "KIEV", "kgst": "KINGST",
    "kirn": "KIRUNA", "kdak": "KODAIK", "kuhl": "KUHLUN", "kula": "KULA", 
#"LAE", "LARC", "LEEDS", "LINCOL", "LINDAU", "LINIGY", "LOMNIC", "LONDON",
#"MAGADA", "MAKAPU", "MAWSON", "MCMURD", "MEXICO", "MINA_A", "MIRNY", "MORIOK", "mosc": "MOSCOW", 
#"MT.NOR", "MT.WAS", "MT.WEL", "MUNCHE", "MURCHI", "MURMAN",
#"NAIN", "NEDERH", "NEWARK", "NORILS", "NORTHF", "NOVOSI",
#"OTTAWA", "oulu": "OULU",
#"PEAWAN", "PIC_DU", "POTCHE", "PRAGUE", "PREDIG", 
#"RESOLU", "RIO_DE", "ROME", 
#"SANAE6", "SANAE8", "SEOUL", "SIMFER", "SNTIAG", "SOUTH", "SULIGY", "SULPHU", "SVERDL", "SWARTH", "SYDNEY", "SYOWA",
#"TASHKE", "TBILIS", "TERRE", "THULE", "TIBET", "TIXIE", "TOKYO", "TSUMEB",
#"UPPSAL", "USHUAI", "UTRECH", 
#"VICTOR", "VOSTOK",
#"WEISSE", "WELLIN", "WILKES", 
    "ykts": "YAKUTS", 
    "zugs": "ZUGSPI"
}

## --------------------------------------------------------------------------
def wdc_name(station):
    name = wdc_map[station]
    while len(name) < 6:
        name += "_"
    return name

## --------------------------------------------------------------------------
def read_rev(options, station, data_type, year, month, day):
    """read revised data
    """

    pressure = [950., 1050.]
    countrate = [.1, 1000.]

    if station in wdc_station:
        value = read_short(options, station, pressure, countrate, year, month, day)

    return value

## --------------------------------------------------------------------------
def read_short(options, station, pressure, countrate, year, month, day = None):
    """
    read one month of WDC data in shortformat
    
Station ID: CALGAR
Station:  CALGARY, CANADA, UNIVERSITY OF CALGARY, CALGARY, CANADA                        
Instrument: 12-NM-64 Corrected to 883.0 mb Standard Pressure and 1964 value Coef =-0.73 %/mb
Latitude (deg.):   51.08  Longitude (deg.): -114.13  Altitude (m): 1128.00
Cut-Off Rigidity (GV):    1.08
Year: 2009  Month:   1
Scaling Factor (SF):   500.0   Constant (CONST):     0.0  Real Counts = (DATA + CONST)*SF
Temporal Resolution: 1 hour
UTC Start Hour:     0.0
    """
    
    
    data_path = '~/data/wdc/SHORTFORMAT'
    data_path = os.path.expanduser(data_path)
    try:
        sname = "%s/%4i/S_%s_%4i.txt" % (data_path, year, wdc_name(station), year)
    except KeyError:
        print "station not defined: %s" % (station)
        return None
        
    try:
        myfile = open(sname, "r")
    except IOError:
        print "error opening %s" % (sname)
        return None

    (dummy, days) = calendar.monthrange(year, month)
    
    data = []
    myinterval = 3600
    SF = 100.
    offset = 0.

    while True:
        line = myfile.readline()
        if not line:
            break  # end of file
        words = line.split()
        if len(words) <= 1:
            # skip empty lines
            continue
        if words[0] == "Scaling":
            # update Scaling Factor and Offset
            SF = float(words[3])
            offset = float(words[6])

        if words[0] != wdc_map[station]:
            # skip non-data lines
            continue
        else:
            thisyear = int(words[1])
            thismonth = int(words[2])
            thisday = int(words[3])
            idx = int(words[4])
            if year == thisyear and month == thismonth and thisday <= days:
                for hour in range(0, 12):
                    mytime = time(hour + (idx-1)*12, 0, 0)
                    mydate = date(year, month, thisday)
                    mydatetime = datetime.combine(mydate, mytime)

                    corr = float(words[5+hour])
                    uncorr = 0.
                    press = 0.
                    if corr == 99999:  # indicates missing data
                        corr = 0.
                    else:
                        corr = SF * (corr + offset)
                        
                    corr = round((corr/ myinterval), 3)
                    
                    uncorr = check_data(uncorr, cr_min=countrate[0], cr_max=countrate[1])
                    press = check_pressure(press, p_min=pressure[0], p_max=pressure[1])
                    corr = check_data(corr, cr_min=countrate[0], cr_max=countrate[1])
                    ceff = corr

                    if 0: # options.verbose > 1
                        print mydatetime, myinterval, uncorr, ceff, corr, press
                    if day == None or day == thisday:
                        data.append([  # order as in NMDB
                                    mydatetime, myinterval, uncorr, ceff, corr, press
                                    ])

    return data
    
## --------------------------------------------------------------------------
def main():
    print "Ready."

    return
## --------------------------------------------------------------------------
if __name__ == '__main__':

    #station = "ahmd" # 1957-1958 (cps: 1.8), 1964 (cps: 7), 1968-1973 (cps: 50)
    station = "chic" # 6.1957-6.1971 (cps: 6)
    #station = "gott" # 7.1957-1.1959 (cps: )
    #station = "zugs" # 7.1957-5.1978 (cps: 60)

    if station == "ahmd":
        year = 1964
        month = 1
        day = None
        pressure = [950., 1050.]
        countrate = [0.5, 200.]
    elif station == "chic":
        year = 1968
        month = 5
        day = None
        pressure = [950., 1050.]
        countrate = [0.1, 1000.]
    elif station == "zugs":
        year = 1978
        month = 4
        day = None
        pressure = [950., 1050.]
        countrate = [15, 240.]
    elif station == "nederh":
        year = 1964
        month = 2
        day = 3
        pressure = [950., 1050.]  # 982 - 1028
        countrate = [1., 10000.]

    data = read_short(None, station, pressure, countrate, year, month, day)
#    print data
    for i in data:
        print i
    sys.exit(0)
